<template>
  <div class="user-info-container">
    <h2 class="page-title">个人信息</h2>
    
    <div class="form-container" v-loading="loading">
      <el-form :model="userForm" :rules="rules" ref="userForm" label-width="100px" class="user-form">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" disabled></el-input>
        </el-form-item>
        
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" placeholder="请输入昵称"></el-input>
        </el-form-item>
        
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            :action="`${baseURL}/api/upload/common`"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="userForm.realName" placeholder="请输入真实姓名"></el-input>
        </el-form-item>
        
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号码"></el-input>
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="userForm.gender">
            <el-radio :label="0">保密</el-radio>
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="生日" prop="birthday">
          <el-date-picker
            v-model="userForm.birthday"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="saveUserInfo" :loading="saving">保存修改</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
      
      <el-divider></el-divider>
      
      <div class="password-change">
        <h3 class="section-title">修改密码</h3>
        
        <el-form :model="passwordForm" :rules="passwordRules" ref="passwordForm" label-width="100px" class="password-form">
          <el-form-item label="当前密码" prop="oldPassword">
            <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入当前密码"></el-input>
          </el-form-item>
          
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码"></el-input>
          </el-form-item>
          
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码"></el-input>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="changePassword" :loading="changingPassword">修改密码</el-button>
            <el-button @click="resetPasswordForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getUserInfo, updateUserInfo, changePassword } from '@/api/user'

export default {
  name: 'UserInfo',
  data() {
    // 确认密码验证
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }
    
    return {
      // 用户信息表单
      userForm: {
        id: '',
        username: '',
        nickname: '',
        avatar: '',
        realName: '',
        phone: '',
        email: '',
        gender: 0,
        birthday: ''
      },
      // 修改密码表单
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      // 表单验证规则
      rules: {
        nickname: [
          { max: 20, message: '昵称长度不能超过20个字符', trigger: 'blur' }
        ],
        realName: [
          { max: 20, message: '姓名长度不能超过20个字符', trigger: 'blur' }
        ],
        phone: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      },
      // 密码表单验证规则
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入当前密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      },
      // 加载状态
      loading: false,
      saving: false,
      changingPassword: false,
      // 上传头像相关
      baseURL: process.env.VUE_APP_BASE_API || 'http://localhost:9999'
    }
  },
  computed: {
    ...mapGetters(['currentUser', 'token']),
    // 上传头像需要的headers
    uploadHeaders() {
      return {
        Authorization: `Bearer ${this.token}`
      }
    }
  },
  created() {
    this.fetchUserInfo()
  },
  methods: {
    // 获取用户信息
    fetchUserInfo() {
      if (!this.currentUser) return
      
      this.loading = true
      
      getUserInfo(this.currentUser.id)
        .then(response => {
          if (response.code == 200) {
            const user = response.data
            this.userForm = {
              id: user.id,
              username: user.username,
              nickname: user.nickname || '',
              avatar: user.avatar || '',
              realName: user.realName || '',
              phone: user.phone || '',
              email: user.email || '',
              gender: user.gender !== undefined ? user.gender : 0,
              birthday: user.birthday || ''
            }
          } else {
            this.$message.error(response.message || '获取用户信息失败')
          }
        })
        .catch(error => {
          console.error('获取用户信息失败', error)
          this.$message.error('获取用户信息失败，请稍后再试')
        })
        .finally(() => {
          this.loading = false
        })
    },
    
    // 保存用户信息
    saveUserInfo() {
      this.$refs.userForm.validate(valid => {
        if (valid) {
          this.saving = true
          
          updateUserInfo(this.userForm)
            .then(response => {
              if (response.code === 200) {
                this.$message.success('保存成功')
                // 更新Vuex中的用户信息
                this.$store.commit('UPDATE_USER_INFO', this.userForm)
              } else {
                this.$message.error(response.message || '保存失败')
              }
            })
            .catch(error => {
              console.error('保存用户信息失败', error)
              this.$message.error('保存失败，请稍后再试')
            })
            .finally(() => {
              this.saving = false
            })
        }
      })
    },
    
    // 重置用户信息表单
    resetForm() {
      this.$refs.userForm.resetFields()
      this.fetchUserInfo()
    },
    
    // 修改密码
    changePassword() {
      this.$refs.passwordForm.validate(valid => {
        if (valid) {
          this.changingPassword = true
          
          // 构建密码修改参数
          const params = {
            userId: this.currentUser.id,
            oldPassword: this.passwordForm.oldPassword,
            newPassword: this.passwordForm.newPassword
          }
          
          changePassword(params)
            .then(response => {
              if (response.code === 200) {
                this.$message.success('密码修改成功，请重新登录')
                // 清空表单
                this.resetPasswordForm()
                // 退出登录
                setTimeout(() => {
                  this.$store.dispatch('logout')
                  this.$router.push('/login')
                }, 1500)
              } else {
                this.$message.error(response.message || '密码修改失败')
              }
            })
            .catch(error => {
              console.error('密码修改失败', error)
              this.$message.error('密码修改失败，请稍后再试')
            })
            .finally(() => {
              this.changingPassword = false
            })
        }
      })
    },
    
    // 重置密码表单
    resetPasswordForm() {
      this.$refs.passwordForm.resetFields()
    },
    
    // 头像上传成功回调
    handleAvatarSuccess(res) {
      if (res.code === 200) {
        this.userForm.avatar = res.data.fileUrl
        this.$message.success('头像上传成功')
      } else {
        this.$message.error(res.message || '头像上传失败')
      }
    },
    
    // 头像上传前的验证
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      
      if (!isJPG) {
        this.$message.error('上传头像图片只能是JPG或PNG格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style scoped>
.user-info-container {
  padding: 20px;
}

.page-title {
  font-size: 20px;
  margin-bottom: 30px;
  color: #333;
}

.section-title {
  font-size: 18px;
  margin-bottom: 20px;
  color: #333;
}

.form-container {
  max-width: 600px;
}

.user-form,
.password-form {
  margin-bottom: 30px;
}

.avatar-uploader {
  width: 120px;
  height: 120px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
}

.password-change {
  margin-top: 30px;
}
</style> 